<template>
	<div class="md-upload-image" :class="{'error--text': errorBucket.length > 0}">
		<span class="subtitle-1">{{ label }}</span>
		<div class="image" :style="{height:height, width:width}" @click="onClick">
			<img :src="data | imageSrc" :height="height" :width="width" alt="" v-show="data">
		</div>
		<div class="v-text-field__details">
			<div class="v-messages error--text" :class="theme === 'dark'? 'theme--dark' :'theme--light'">
				<div class="v-messages__wrapper">
					{{ errorBucket.length > 0 ? errorBucket[0] : '' }}
				</div>
			</div>
		</div>
		<input type="file" accept="image/*" @change="fileInputChange" ref="file" hidden/>
	</div>
</template>

<script>
import MdMVVMObject from '@/common/mixins/MdMVVMObject';
import {mapGetters} from 'vuex';
import FileApi from '@/common/api/FileApi';

export default {
	name: 'MdUploadImage',
	mixins: [MdMVVMObject],
	inject: ['form'],
	props: {
		label: String,
		height: {
			type: String,
			default: '100px'
		},
		width: {
			type: String,
			default: '100px'
		},
		rules: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			valid: false,
			fileValue: undefined,
			errorBucket: []
		}
	},
	computed: {
		...mapGetters({theme: 'mainTheme'})
	},
	created() {
		this.form && this.form.inputs.push(this)
	},
	methods: {
		validate(force = false, value = undefined) {
			const errorBucket = []
			value = value || this.data

			for (let index = 0; index < this.rules.length; index++) {
				const rule = this.rules[index]
				const valid = typeof rule === 'function' ? rule(value) : rule

				if (valid === false || typeof valid === 'string') {
					errorBucket.push(valid || '')
				} else if (typeof valid !== 'boolean') {
					console.error(`Rules should return a string or boolean, received '${typeof valid}' instead`, this)
				}
			}

			this.errorBucket = errorBucket
			this.valid = errorBucket.length === 0
			console.info(errorBucket)
			return this.valid
		},
		onClick() {
			this.$refs.file.click();
		},
		fileInputChange(event) {
			let data = new FormData();
			if (event.target.files.length === 0) return;
			data.append('file', event.target.files[0])
			this.$refs.file.value = ''
			FileApi.upload.image(data).then(res => {
				this.$utils.responseHandler(res, true, true).then(({data}) => {
					this.data = data.savePath;
					this.validate()
				})
			})
		}
	},

	watch: {}
}
</script>

<style scoped lang="scss">
.md-upload-image {
	span {
		display: block;
		line-height: 30px;
	}

	&.error--text {
		.image {
			border-color: #ff5252;
		}
	}

	.image {
		cursor: pointer;
		border-radius: 3px;
		border: 1px dotted #e6f7ff;
	}
}
</style>